import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter,Route } from 'react-router-dom';
import { Provider } from 'react-redux';

/**
 * 渲染页面
 * @param {*} store 
 * @param {*} routes 路由配置对象
 * @param {*} req    请求对象
 */
export const render = (store, routes, req) => {
        const HomeContent = renderToString(
            <Provider store={store}>
                <StaticRouter context={{}} location={req.path}>
                    <div>
                        {
                            routes.map(route => (
                                <Route {...route} />
                            ))
                        }
                    </div>
                </StaticRouter>
            </Provider>
        );
        return `
            <!DOCTYPE html>
            <html lang="en">
            <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>Document</title>
            </head>
            <body>
            <div id="root">${HomeContent}</div>
            <script>
            window.context = {
                state: ${JSON.stringify(store.getState())}
            }
            </script>
            <script src="/index.js"></script>
            </body>
            </html>
        `;
}
